//
//  MainViewController.m
//  1gene
//
//  Created by 1jiyin on 16/4/5.
//  Copyright © 2016年 1jiyin. All rights reserved.
//

#import "MainViewController.h"
#import "AppDelegate.h"
#import "UMSocial.h"
#import "UMSocialQQHandler.h"
#import "UMSocialWechatHandler.h"
#import "UIView+TiShiMessage.h"
@interface MainViewController ()<UITextFieldDelegate>
@property(nonatomic,copy)UIView *backGroundView;
@property(nonatomic,copy)UIImageView *backGroundImageView;
@property(nonatomic,assign)CGRect originFrame;
@property(nonatomic,copy)UITextField *userTextField;
@property(nonatomic,copy)UITextField *passwordTextField;
@property(nonatomic,copy)MyTableView *myTable;

@property(nonatomic,copy)UIScrollView *myScroll;

/*
 *返回的头像
 */
@property(nonatomic,copy)UIImage *userHeadImage;

@property(nonatomic,copy)NSTimer *myTimer;
@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self createUI];
    //[self startTimer];
    // Do any additional setup after loading the view.
}
//开启定时器
-(void)startTimer
{
    if(_myTimer==nil)
    {
        _myTimer=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerRun) userInfo:nil repeats:NO];
    }
}
-(void)timerRun
{
    [self getHTTPData];
}
-(void)getHTTPData
{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSDictionary *dic=[user objectForKey:@"messageDic"];
    if (dic!=nil) {
        [self sendNotification:dic[@"topic"] :dic[@"content"]];
        
    }
}
-(void)sendNotification:(NSString *)topic :(NSString *)content
{
    //定义本地通知对象
    UILocalNotification *notification=[[UILocalNotification alloc]init];
    //设置调用时间
    notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:1.0];//通知触发的时间，10s以后
    notification.repeatInterval=1;//通知重复次数
    //notification.repeatCalendar=[NSCalendar currentCalendar];//当前日历，使用前最好设置时区等信息以便能够自动同步时间
    
    //设置通知属性
    notification.alertBody=content; //通知主体
    //notification.applicationIconBadgeNumber++;//应用程序图标右上角显示的消息数
    notification.alertAction=@"打开应用"; //待机界面的滑动动作提示
    // notification.alertLaunchImage=[[NSBundle mainBundle] pathForResource:@"2.jpg" ofType:nil];//通过点击通知打开应用时的启动图片,这里使用程序启动图片
    notification.soundName=UILocalNotificationDefaultSoundName;//收到通知时播放的声音，默认消息声音
    //notification.soundName=@"msg.caf";//通知声音（需要真机才能听到声音）
    
    //设置用户信息
    notification.userInfo=@{@"id":@1,@"user":@"Kenshin Cui"};//绑定到通知上的其他附加信息
    
    //调用通知
    //[[UIApplication sharedApplication] scheduleLocalNotification:notification];
    [[UIApplication sharedApplication]presentLocalNotificationNow:notification];
}
-(void)createUI
{
    // 判断之前用户是否登陆过，并且没有退出登录，如果没有退出登录就直接自动登录
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *phone=[user objectForKey:@"userPhone"];
    NSString *password=[user objectForKey:@"userPassword"];
    NSLog(@"手机号：%@，密码：%@", phone, password);
    
    if (phone == nil || password == nil) {
        // 说明用户之前没有登录过或者用户手动退出
        //背景图片
        UIImageView *backGroundView=[[UIImageView alloc]initWithFrame:self.view.bounds];
        backGroundView.userInteractionEnabled=YES;
        backGroundView.image=[UIImage imageNamed:@"loginBackground-6.png"];
        [self.view addSubview:backGroundView];
        
        
        
        
        
        
        UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        scroll.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height+100);
        scroll.showsVerticalScrollIndicator = NO;
        [self.view addSubview:scroll];
        _myScroll = scroll;
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame=CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height+100);
        [btn addTarget:self action:@selector(selfBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:btn];
        
        
        //跳过
        UIButton *stepToBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        stepToBtn.frame=CGRectMake(self.view.frame.size.width-50-20, 30, 50, 30);
        stepToBtn.titleLabel.font=[UIFont systemFontOfSize:15];
        [stepToBtn setTitle:@"跳过" forState:UIControlStateNormal];
        [stepToBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [stepToBtn addTarget:self action:@selector(stepToBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:stepToBtn];
        
        
        //背景视图
        _backGroundView=[[UIView alloc]init];
        
        
        //用户名
        UITextField *userTextField=[[UITextField alloc]initWithFrame:CGRectMake(20, 0, self.view.frame.size.width-20*2, 50)];
        
        UIView *userLeftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
        
        UIImageView *userLeftImgView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"userName-1-1.png"]];
        userLeftImgView.frame=CGRectMake(20, (50-47*0.6)/2.0, 41*0.6, 47*0.6);
        [userLeftView addSubview:userLeftImgView];
        
        
        
        
        userTextField.clearButtonMode=UITextFieldViewModeWhileEditing;
        userTextField.leftView=userLeftView;
        userTextField.placeholder=@"手机号码";
        userTextField.leftViewMode=UITextFieldViewModeAlways;
        userTextField.backgroundColor=[UIColor whiteColor];
        userTextField.layer.borderColor=[UIColor colorWithRed:238 green:232 blue:236 alpha:1].CGColor;
        userTextField.layer.borderWidth=1.0;
        userTextField.layer.cornerRadius=5.0;
        userTextField.keyboardType=UIKeyboardTypeNumberPad;
        [_backGroundView addSubview:userTextField];
        
        
        //密码
        UITextField *passwordTextField=[[UITextField alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(userTextField.frame)+10, self.view.frame.size.width-20*2, 50)];
        
        UIView *passwordLeftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
        
        UIImageView *passworLeftImgView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"password-3-1.png"]];
        passworLeftImgView.frame=CGRectMake(20, (50-47*0.6)/2.0, 41*0.6, 47*0.6);
        [passwordLeftView addSubview:passworLeftImgView];
        
        
        passwordTextField.leftView=passwordLeftView;
        passwordTextField.placeholder=@"密码";
        passwordTextField.leftViewMode=UITextFieldViewModeAlways;
        passwordTextField.backgroundColor=[UIColor whiteColor];
        passwordTextField.layer.borderColor=[UIColor colorWithRed:238 green:232 blue:236 alpha:1].CGColor;
        passwordTextField.layer.borderWidth=1.0;
        passwordTextField.layer.cornerRadius=5.0;
        passwordTextField.secureTextEntry=YES;
        //passwordTextField.keyboardType=UIKeyboardTypeNamePhonePad;
        passwordTextField.clearButtonMode=UITextFieldViewModeWhileEditing;
        passwordTextField.delegate=self;
        passwordTextField.returnKeyType=UIReturnKeyDone;
        [_backGroundView addSubview:passwordTextField];
        
        
        //监听
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardIsShow:) name:UIKeyboardDidShowNotification object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardIsHidden:) name:UIKeyboardDidHideNotification object:nil];
        
        _backGroundView.frame=CGRectMake(0, self.view.frame.size.height/2.0-40, self.view.frame.size.width, userTextField.frame.size.height*2+10);
        [scroll addSubview:_backGroundView];
        _originFrame=_backGroundView.frame;
        
        
        CGFloat btn_w=self.view.frame.size.width/3.0;
        CGFloat btn_h=35;
        //马上登陆
        UIButton *loginBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        loginBtn.frame=CGRectMake(btn_w, CGRectGetMaxY(_backGroundView.frame)+20, btn_w, btn_h);
        loginBtn.backgroundColor=[UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1];
        [loginBtn setTitle:@"马上登陆" forState:UIControlStateNormal];
        [loginBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        loginBtn.tag=2;
        loginBtn.layer.borderColor=[UIColor colorWithRed:238 green:232 blue:236 alpha:1].CGColor;
        loginBtn.layer.borderWidth=1.0;
        loginBtn.layer.cornerRadius=5.0;
        [loginBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:loginBtn];
        
        //忘记密码
        UIButton *forgotPasswordBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        forgotPasswordBtn.frame=CGRectMake(btn_w, CGRectGetMaxY(loginBtn.frame)+10, btn_w, btn_h);
        forgotPasswordBtn.backgroundColor=[UIColor colorWithRed:250/255.0 green:250/255.0 blue:251/255.0 alpha:1];
        [forgotPasswordBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
        [forgotPasswordBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        forgotPasswordBtn.tag=3;
        forgotPasswordBtn.layer.borderColor=[UIColor colorWithRed:238 green:232 blue:236 alpha:1].CGColor;
        forgotPasswordBtn.layer.borderWidth=1.0;
        forgotPasswordBtn.layer.cornerRadius=5.0;
        [forgotPasswordBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:forgotPasswordBtn];
        
        //用户注册
        UIButton *registerBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        registerBtn.frame=CGRectMake(btn_w, CGRectGetMaxY(forgotPasswordBtn.frame)+10, btn_w, btn_h);
        registerBtn.backgroundColor=[UIColor colorWithRed:250/255.0 green:250/255.0 blue:251/255.0 alpha:1];
        [registerBtn setTitle:@"用户注册" forState:UIControlStateNormal];
        [registerBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        registerBtn.tag=4;
        registerBtn.layer.borderColor=[UIColor colorWithRed:238 green:232 blue:236 alpha:1].CGColor;
        registerBtn.layer.borderWidth=1.0;
        registerBtn.layer.cornerRadius=5.0;
        [registerBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:registerBtn];
        
        //
        UIView *l1=[[UIView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(registerBtn.frame)+20, (self.view.frame.size.width-60-10*2)/2.0, 0.5)];
        l1.backgroundColor=[UIColor grayColor];
        [scroll addSubview:l1];
        
        UIView *l2=[[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(l1.frame)+60, CGRectGetMaxY(registerBtn.frame)+20, (self.view.frame.size.width-60-10*2)/2.0, 0.5)];
        l2.backgroundColor=[UIColor grayColor];
        [scroll addSubview:l2];
        UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(l1.frame), CGRectGetMaxY(registerBtn.frame)+20-7, 60, 14)];
        lab.text=@"第三方登录";
        lab.textColor=[UIColor grayColor];
        lab.font=[UIFont systemFontOfSize:12];
        lab.textAlignment=NSTextAlignmentCenter;
        [scroll addSubview:lab];
        
        
        CGFloat b_h=40;
        CGFloat jiange=20;
        NSArray *imgArr=@[@{@"image":@"weixin"},@{@"image":@"qq"},@{@"image":@"weibo"}];
        NSLog(@"=========%ld",imgArr.count);
        for (int i=0; i<imgArr.count; i++) {
            UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
            NSLog(@"=========%f",jiange+(jiange+b_h)*i);
            btn.frame=CGRectMake((self.view.frame.size.width-20*4-40*3)/2.0+20+(jiange+b_h)*i, CGRectGetMaxY(lab.frame)+3, b_h, b_h);
            [btn setBackgroundImage:[UIImage imageNamed:imgArr[i][@"image"]] forState:UIControlStateNormal];
            btn.tag=i;
            [btn addTarget:self action:@selector(threeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [scroll addSubview:btn];
        }
        _userTextField=userTextField;
        _passwordTextField=passwordTextField;
        _backGroundImageView=backGroundView;
    } else if (phone != nil && password != nil) {
        NSLog(@"自动登录");
        // 说明用户已经登录过，要自动登录
        //背景图片
        UIImageView *backGroundView=[[UIImageView alloc]initWithFrame:self.view.bounds];
        backGroundView.userInteractionEnabled=YES;
        backGroundView.image=[UIImage imageNamed:@"loginBackground-6.png"];
        [self.view addSubview:backGroundView];
        
        
        
        
        
        
        UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        scroll.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height+100);
        scroll.showsVerticalScrollIndicator = NO;
        [self.view addSubview:scroll];
        _myScroll = scroll;
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame=CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height+100);
        [btn addTarget:self action:@selector(selfBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:btn];
        
        
        //跳过
        UIButton *stepToBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        stepToBtn.frame=CGRectMake(self.view.frame.size.width-50-20, 30, 50, 30);
        stepToBtn.titleLabel.font=[UIFont systemFontOfSize:15];
        [stepToBtn setTitle:@"跳过" forState:UIControlStateNormal];
        [stepToBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [stepToBtn addTarget:self action:@selector(stepToBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:stepToBtn];
        
        
        //背景视图
        _backGroundView=[[UIView alloc]init];
        
        
        //用户名
        UITextField *userTextField=[[UITextField alloc]initWithFrame:CGRectMake(20, 0, self.view.frame.size.width-20*2, 50)];
        
        UIView *userLeftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
        
        UIImageView *userLeftImgView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"userName-1-1.png"]];
        userLeftImgView.frame=CGRectMake(20, (50-47*0.6)/2.0, 41*0.6, 47*0.6);
        [userLeftView addSubview:userLeftImgView];
        
        
        
        
        userTextField.clearButtonMode=UITextFieldViewModeWhileEditing;
        userTextField.leftView=userLeftView;
        userTextField.placeholder=@"手机号码";
        userTextField.text = phone;
        userTextField.leftViewMode=UITextFieldViewModeAlways;
        userTextField.backgroundColor=[UIColor whiteColor];
        userTextField.layer.borderColor=[UIColor colorWithRed:238 green:232 blue:236 alpha:1].CGColor;
        userTextField.layer.borderWidth=1.0;
        userTextField.layer.cornerRadius=5.0;
        userTextField.keyboardType=UIKeyboardTypeNumberPad;
        [_backGroundView addSubview:userTextField];
        
        
        //密码
        UITextField *passwordTextField=[[UITextField alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(userTextField.frame)+10, self.view.frame.size.width-20*2, 50)];
        
        UIView *passwordLeftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
        
        UIImageView *passworLeftImgView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"password-3-1.png"]];
        passworLeftImgView.frame=CGRectMake(20, (50-47*0.6)/2.0, 41*0.6, 47*0.6);
        [passwordLeftView addSubview:passworLeftImgView];
        
        
        passwordTextField.leftView=passwordLeftView;
        passwordTextField.placeholder=@"密码";
        passwordTextField.text = password;
        passwordTextField.leftViewMode=UITextFieldViewModeAlways;
        passwordTextField.backgroundColor=[UIColor whiteColor];
        passwordTextField.layer.borderColor=[UIColor colorWithRed:238 green:232 blue:236 alpha:1].CGColor;
        passwordTextField.layer.borderWidth=1.0;
        passwordTextField.layer.cornerRadius=5.0;
        passwordTextField.secureTextEntry=YES;
        //passwordTextField.keyboardType=UIKeyboardTypeNamePhonePad;
        passwordTextField.clearButtonMode=UITextFieldViewModeWhileEditing;
        passwordTextField.delegate=self;
        passwordTextField.returnKeyType=UIReturnKeyDone;
        [_backGroundView addSubview:passwordTextField];
        
        
        //监听
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardIsShow:) name:UIKeyboardDidShowNotification object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardIsHidden:) name:UIKeyboardDidHideNotification object:nil];
        
        _backGroundView.frame=CGRectMake(0, self.view.frame.size.height/2.0-40, self.view.frame.size.width, userTextField.frame.size.height*2+10);
        [scroll addSubview:_backGroundView];
        _originFrame=_backGroundView.frame;
        
        
        CGFloat btn_w=self.view.frame.size.width/3.0;
        CGFloat btn_h=35;
        //马上登陆
        UIButton *loginBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        loginBtn.frame=CGRectMake(btn_w, CGRectGetMaxY(_backGroundView.frame)+20, btn_w, btn_h);
        loginBtn.backgroundColor=[UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1];
        [loginBtn setTitle:@"马上登陆" forState:UIControlStateNormal];
        [loginBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        loginBtn.tag=2;
        loginBtn.layer.borderColor=[UIColor colorWithRed:238 green:232 blue:236 alpha:1].CGColor;
        loginBtn.layer.borderWidth=1.0;
        loginBtn.layer.cornerRadius=5.0;
        [loginBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:loginBtn];
        
        //忘记密码
        UIButton *forgotPasswordBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        forgotPasswordBtn.frame=CGRectMake(btn_w, CGRectGetMaxY(loginBtn.frame)+10, btn_w, btn_h);
        forgotPasswordBtn.backgroundColor=[UIColor colorWithRed:250/255.0 green:250/255.0 blue:251/255.0 alpha:1];
        [forgotPasswordBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
        [forgotPasswordBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        forgotPasswordBtn.tag=3;
        forgotPasswordBtn.layer.borderColor=[UIColor colorWithRed:238 green:232 blue:236 alpha:1].CGColor;
        forgotPasswordBtn.layer.borderWidth=1.0;
        forgotPasswordBtn.layer.cornerRadius=5.0;
        [forgotPasswordBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:forgotPasswordBtn];
        
        //用户注册
        UIButton *registerBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        registerBtn.frame=CGRectMake(btn_w, CGRectGetMaxY(forgotPasswordBtn.frame)+10, btn_w, btn_h);
        registerBtn.backgroundColor=[UIColor colorWithRed:250/255.0 green:250/255.0 blue:251/255.0 alpha:1];
        [registerBtn setTitle:@"用户注册" forState:UIControlStateNormal];
        [registerBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        registerBtn.tag=4;
        registerBtn.layer.borderColor=[UIColor colorWithRed:238 green:232 blue:236 alpha:1].CGColor;
        registerBtn.layer.borderWidth=1.0;
        registerBtn.layer.cornerRadius=5.0;
        [registerBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:registerBtn];
        
        //
        UIView *l1=[[UIView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(registerBtn.frame)+20, (self.view.frame.size.width-60-10*2)/2.0, 0.5)];
        l1.backgroundColor=[UIColor grayColor];
        [scroll addSubview:l1];
        
        UIView *l2=[[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(l1.frame)+60, CGRectGetMaxY(registerBtn.frame)+20, (self.view.frame.size.width-60-10*2)/2.0, 0.5)];
        l2.backgroundColor=[UIColor grayColor];
        [scroll addSubview:l2];
        UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(l1.frame), CGRectGetMaxY(registerBtn.frame)+20-7, 60, 14)];
        lab.text=@"第三方登录";
        lab.textColor=[UIColor grayColor];
        lab.font=[UIFont systemFontOfSize:12];
        lab.textAlignment=NSTextAlignmentCenter;
        [scroll addSubview:lab];
        
        
        CGFloat b_h=40;
        CGFloat jiange=20;
        NSArray *imgArr=@[@{@"image":@"weixin"},@{@"image":@"qq"},@{@"image":@"weibo"}];
        NSLog(@"=========%ld",imgArr.count);
        for (int i=0; i<imgArr.count; i++) {
            UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
            NSLog(@"=========%f",jiange+(jiange+b_h)*i);
            btn.frame=CGRectMake((self.view.frame.size.width-20*4-40*3)/2.0+20+(jiange+b_h)*i, CGRectGetMaxY(lab.frame)+3, b_h, b_h);
            [btn setBackgroundImage:[UIImage imageNamed:imgArr[i][@"image"]] forState:UIControlStateNormal];
            btn.tag=i;
            [btn addTarget:self action:@selector(threeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [scroll addSubview:btn];
        }
        _userTextField=userTextField;
        _passwordTextField=passwordTextField;
        _backGroundImageView=backGroundView;
        
        // 登录
        [self startLogin];
    }
    
   
}

-(void)selfBtnClick:(UIButton *)sender
{
    [self.navigationController.view endEditing:YES];
    NSLog(@"111111");
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"执行");
    [self.view endEditing:YES];
    return YES;
}

//跳过
-(void)stepToBtnClick:(UIButton *)sender
{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    [user setObject:nil forKey:@"token"];
    [user setObject:nil forKey:@"userId"];
    [user setObject:nil forKey:@"userName"];
    [user setObject:nil forKey:@"userPhone"];
    [user setObject:nil forKey:@"userPassword"];
    [user setObject:@"tiaoguo" forKey:@"tiaoguo"];
    [user synchronize];
    AppDelegate *app=[UIApplication sharedApplication].delegate;
    [app showMainViewController:1];
}

//第三方登陆
-(void)threeBtnClick:(UIButton *)sender
{
    if(sender.tag==0){
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
        
        snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
            NSLog(@"返回微信的数据=====%@",response);
            if (response.responseCode == UMSResponseCodeSuccess) {
                
                UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary]valueForKey:snsPlatform.platformName];
                
                NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
                
                [self threePartyLogin:@"weixin" AndUsid:snsAccount.usid AndName:snsAccount.userName AndAccessToken:snsAccount.accessToken];
            }
            
        });
    }else if (sender.tag==1){
            UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
        
            snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
         NSLog(@"返回QQ的数据=====%@",response);
                //          获取微博用户名、uid、token等
        
                if (response.responseCode == UMSResponseCodeSuccess) {
        
                    UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:snsPlatform.platformName];
                    
                    NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
                    [self threePartyLogin:@"qq" AndUsid:snsAccount.usid AndName:snsAccount.userName AndAccessToken:snsAccount.accessToken];
                }else{
                    NSLog(@"=========%@",response);
                }
            }
        );
    }else if (sender.tag==2){
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
        
        snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
             NSLog(@"返回新浪的数据=====%@",response);
            //          获取微博用户名、uid、token等
            
            if (response.responseCode == UMSResponseCodeSuccess) {
                
                UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:snsPlatform.platformName];
                
                NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
                [self threePartyLogin:@"weibo" AndUsid:snsAccount.usid AndName:snsAccount.userName AndAccessToken:snsAccount.accessToken];
            }});
    }
}
#pragma mark 按钮响应
-(void)btnClick:(UIButton *)sender
{
    if (sender.tag==1) {

    }else if (sender.tag==2){
        //马上登陆
        [self startLogin];
    }else if (sender.tag==3){
        //忘记密码
        ForgotPasswordViewController *vc=[[ForgotPasswordViewController alloc]init];
        vc.hideNavigationBar=YES;
        vc.passwordType = 1; // 忘记登录的密码
        self.navigationController.navigationBar.hidden=NO;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (sender.tag==4){
        //用户注册
        RegisterViewController *vc=[[RegisterViewController alloc]init];
        self.navigationController.navigationBar.hidden=NO;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark 登陆
-(void)startLogin
{
    [self.view endEditing:YES];
    if (_userTextField.text.length>0&&_passwordTextField.text.length>0) {
        //[self getHttpData];
//        NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
//        [user setObject:@"123456" forKey:@"userId"];
//        [user synchronize];
//        AppDelegate *app=[UIApplication sharedApplication].delegate;
//        [app showMainViewController:1];
        
            [self getLoginHttpData];

        
        
        
        
    }else if(_userTextField.text.length==0&&_passwordTextField.text.length==0){
        [self showMessageWithContent:@"用户名和密码不能为空"];
    }else{
        [self showMessageWithContent:@"用户名或密码错误"];
    }
//    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
//    [user setObject:@"1" forKey:@"UserName"];
//    [user setObject:@"1" forKey:@"Password"];
//    [user synchronize];
}

-(void)showMessageWithContent:(NSString *)content
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:content delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert show];
}


#pragma mark 显示键盘
-(void)keyBoardIsShow:(NSNotification *)notify
{
    CGRect currentFrame = _backGroundView.frame;
    CGRect kbFrame=[[notify.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
    if (CGRectGetMaxY(_backGroundView.frame)<kbFrame.origin.y) {
        
    }else{
        currentFrame.origin.y=kbFrame.origin.y-currentFrame.size.height;
        _backGroundView.frame=currentFrame;
        // NSLog(@"%@",notify);
    }
    
    //    [UIView animateWithDuration:0.01 animations:^{
    //       _backGroundView.frame=currentFrame;
    //    }];
}

#pragma mark 隐藏键盘
-(void)keyBoardIsHidden:(NSNotification *)notify
{
    _backGroundView.frame=_originFrame;
}

#pragma mark  计算键盘的高度
-(CGFloat)keyboardEndingFrameHeight:(NSDictionary *)userInfo
{
    CGRect keyboardEndingUncorrectedFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGRect keyboardEndingFrame = [self.view convertRect:keyboardEndingUncorrectedFrame fromView:nil];
    return keyboardEndingFrame.size.height;
}
#pragma mark 关闭键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_myScroll endEditing:YES];
    NSLog(@".....");
    [_userTextField resignFirstResponder];
    [_passwordTextField resignFirstResponder];
}


-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden=YES;
}



//登陆
-(void)getLoginHttpData
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    [self.view isLoading:YES];
    NSDictionary *paramDic=@{@"phone":_userTextField.text,@"password":_passwordTextField.text};
    
    [manager POST:Login parameters:paramDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"responseObject = %@+", responseObject);
//        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//        if (dic.count == 1) {
//            NSDictionary *statusDic = [dic valueForKey:@"status"];
//            NSString *msgString = [statusDic valueForKey:@"msg"];
//            
//                if ([msgString isEqualToString:@"user login at another device"]) {
//                    NSLog(@"说明在第一台设备上登陆成功，需要在第一台设备上退出");
//                    [self addQuitFirstSheBeiAlert];
//            }
//        } else {
//            NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//            NSLog(@"login=======%@",dic);
//            if (dic) {
//                NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
//                [user setObject:dic[@"token"] forKey:@"token"];
//                [user setObject:dic[@"user"][@"id"] forKey:@"userId"];
//                [user setObject:dic[@"user"][@"name"] forKey:@"userName"];
//                [user setObject:dic[@"user"][@"phone"] forKey:@"userPhone"];
//                [user setObject:_passwordTextField.text forKey:@"userPassword"];
//                [user setObject:dic[@"user"][@"avatar_url"] forKey:@"userHeadImage"];
//                if ([dic[@"user"][@"rong_token"] isKindOfClass:[NSNull class]]) {
//                    
//                }else{
//                    [user setObject:dic[@"user"][@"rong_token"] forKey:@"rong_token"];
//                }
//                [user synchronize];
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    AppDelegate *app=[UIApplication sharedApplication].delegate;
//                    [app showMainViewController:1];
//                });
//                
//            }
//        }
        
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"login=======%@",dic);
        if (dic) {
            NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
            [user setObject:dic[@"token"] forKey:@"token"];
            [user setObject:dic[@"user"][@"id"] forKey:@"userId"];
            [user setObject:dic[@"user"][@"name"] forKey:@"userName"];
            [user setObject:dic[@"user"][@"phone"] forKey:@"userPhone"];
            [user setObject:_passwordTextField.text forKey:@"userPassword"];
            [user setObject:dic[@"user"][@"avatar_url"] forKey:@"userHeadImage"];
            if ([dic[@"user"][@"rong_token"] isKindOfClass:[NSNull class]]) {
                
            }else{
                [user setObject:dic[@"user"][@"rong_token"] forKey:@"rong_token"];
            }
            [user synchronize];
            dispatch_async(dispatch_get_main_queue(), ^{
                AppDelegate *app=[UIApplication sharedApplication].delegate;
                [app showMainViewController:1];
            });
            
        }

       
        
        
       

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.view isLoading:NO];
        [self.view showTiShiMessage:@"用户名或密码错误"];
        NSLog(@"error====%@",error.localizedDescription);
    }];
    
}



//第三方登录
-(void)threePartyLogin:(NSString *)platform AndUsid:(NSString *)usid AndName:(NSString *)name AndAccessToken:(NSString *)access_token
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    [self.view isLoading:YES];
    NSDictionary *params=@{@"platform":platform,@"usid":usid,@"name":name,@"access_token":access_token};
    [manager POST:ThreeLogin parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"第三方登录%@",dic);
        if (dic) {
            NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
            [user setObject:dic[@"token"] forKey:@"token"];
            [user setObject:dic[@"user"][@"id"] forKey:@"userId"];
            [user setObject:dic[@"user"][@"name"] forKey:@"userName"];
            [user setObject:dic[@"user"][@"rong_token"] forKey:@"rong_token"];
            [user setObject:dic[@"user"][@"avatar_url"] forKey:@"userHeadImage"];
            [user synchronize];
            dispatch_async(dispatch_get_main_queue(), ^{
                AppDelegate *app=[UIApplication sharedApplication].delegate;
                [app showMainViewController:1];
            });
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error%@",error.localizedDescription);
        [self.view showTiShiMessage:@"服务器繁忙"];
        [self.view isLoading:NO];
    }];
    
    
    
}

#pragma mark - 添加在退出第一台设备的提醒框
- (void)addQuitFirstSheBeiAlert
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"警告" message:@"该账号已经在另一台设备上登陆，您确定要顶替么" preferredStyle:UIAlertControllerStyleAlert];
    // 修改标题颜色
    NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"警告"];
    [title addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
    [title addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 2)];
    [alertVC setValue:title forKey:@"attributedTitle"];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"发送消息");
    }];
    [alertVC addAction:sureAction];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
